import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author 徐志荣
 * @date 2023/4/2 16:03
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serveIP;
    private int severPort;

    //对于客户端来说,不需要显示关联端口
    //不代表没有端口,而是系统自动分配了一个空闲的端口
    public UdpEchoClient(String serverIP,int serverport) throws SocketException {
        socket  = new DatagramSocket();
        this.serveIP = serverIP;
        this.severPort = serverport;
    }
    public void start() throws IOException {
        //通过客户端可以多次和服务器进行交互
        while(true){
            //1. 先从控制台,读取一个字符串过来
            Scanner scanner = new Scanner(System.in);
            System.out.println("-> ");
            String request = scanner.next();

            //2. 把字符串构成 UDP packet, 并进行发送
            DatagramPacket requestPacket=  new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serveIP),severPort);
            socket.send(requestPacket);
            //3. 客户端尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4. 把响应数据转换成String 显示出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("req: %s , resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
